//
//  InformationViewController.m
//  用户信息设置
//
//  Created by 周述坚 on 16/11/13.
//  Copyright © 2016年 周述坚. All rights reserved.
//

#import "JPInformationViewController.h"
#import "JPInformationTableViewCell.h"
#import "JPPresentationController.h"
#import "JPSecondViewController.h"
#import "JPPresentationController.h"
#import "JPPhotoPickManager.h"
#import "JPFMDatabaseQueueManager.h"
#import <SVProgressHUD.h>
#import "HMAdditions.h"


#define width self.view.bounds.size.width
#define heigth self.view.bounds.size.height

@interface JPInformationViewController () <UITableViewDataSource,UITableViewDelegate,UIPickerViewDelegate,UIViewControllerTransitioningDelegate>

@property (nonatomic,strong)NSArray *information;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,weak)UIImageView *imageview;

@end

@implementation JPInformationViewController {
    JPFMDatabaseQueueManager *_manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.title = @"个人信息";
    [self setupUI];
    self.information = @[@"姓名",@"性别",@"证件号码",@"联系方式",@"身高",@"体重",@"籍贯",@"常住地" ];
    
    // 获取单例对象
    _manager = [JPFMDatabaseQueueManager sharedManager];
    
    // 首先传入空数据
    NSString *insertSQL = @"insert into t_person(name) values(?);";
    [self update:insertSQL date:@""];
}

/**
 *  初始化界面
 */
- (void)setupUI {
    // 设置表头
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, 200)];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, width, 200)];
    [headView addSubview:imageView];
    imageView.userInteractionEnabled = YES;
    
    // 设置头像
    UIImageView *headPortrait = [[UIImageView alloc] init];
    self.imageview = headPortrait;
    [imageView addSubview:headPortrait];
    headPortrait.frame = CGRectMake(width*0.5 -30, 120, 60, 60);
    
    //判断是否在本地沙盒里面有没有图片
    // NSArray
    NSString *paths = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *casesPath = [paths stringByAppendingPathComponent:@"image.data"];
    NSArray *imageArr = [NSKeyedUnarchiver unarchiveObjectWithFile:casesPath];
    if (imageArr.lastObject == nil) {
        headPortrait.image = [UIImage imageNamed:@"mao.jpeg"];
    } else {
        headPortrait.image = imageArr.lastObject;
    }
    
    // 开启交互 添加手势
    headPortrait.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headViewChange:)];
    [headPortrait addGestureRecognizer:tapGesture];
    
    // 设置圆形
    headPortrait.layer.masksToBounds = YES;
    headPortrait.layer.cornerRadius = 30;
    [imageView addSubview:headPortrait];
    
    // 创建tableView
    imageView.image = [UIImage imageNamed:@"information01.jpg"];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableHeaderView = headView;
    
    // 添加到页面 Y
    [self.tableView registerNib:[UINib nibWithNibName:@"JPInformationTableViewCell" bundle:nil]  forCellReuseIdentifier:@"JPInformationTableViewCell"];
    [self.view addSubview:self.tableView];
}

#pragma mark - tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.information.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JPInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JPInformationTableViewCell" forIndexPath:indexPath];
    cell.nameLabel.text = self.information[indexPath.row];
    cell.nameLabel.font = [UIFont systemFontOfSize:16];
    cell.nameLabel.textColor = [UIColor hm_colorWithRed:62 green:62 blue:62];
    cell.inforLabel.font = [UIFont systemFontOfSize:14];
    cell.inforLabel.textColor = [UIColor hm_colorWithRed:120 green:120 blue:120];
    
    // 判断本地是否有数据- 如果有,就从数据库中获取,如果没有 就创建
    NSString *querySQL = @"select name,sex ,IDNumber,tell,height,weight,native,address from t_person where id = 1;";
    
    [_manager inDatabase:^(FMDatabase *db) {
        cell.inforLabel.hidden = NO;
        // 执行查询SQL语句
        FMResultSet *rs = [db executeQuery:querySQL];
        // 遍历结果集,一条一条的取出记录
        while ([rs next]) {
            NSString *string ;
            switch (indexPath.row) {
                case 0:
                    string = @"name";
                    break;
                case 1:
                    string = @"sex";
                    break;
                case 2:
                    string = @"IDNumber";
                    break;
                case 3:
                    string = @"tell";
                    break;
                case 4:
                    string = @"height";
                    break;
                case 5:
                    string = @"weight";
                    break;
                case 6:
                    string = @"native";
                    break;
                case 7:
                    string = @"address";
                    break;
                default:
                    break;
            }
            // 取出对应的值
            cell.inforLabel.text =  [rs stringForColumn:string];
        }
    }];
    return cell;
}

#pragma make - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:
            [self setName:indexPath];
            break;
            
        case 1:
            [self setGender:indexPath];
            break;
            
        case 2:
            [self setName:indexPath];
            break;
            
        case 3:
            [self setName:indexPath];
            break;
            
        case 4:
            [self setPrompt:indexPath];
            break;
            
        case 5:
            [self setPrompt:indexPath];
            break;
        case 6:
            [self setPrompt:indexPath];
            break;
            
        case 7:
            [self setPrompt:indexPath];
            break;
            
        default:
            break;
    }
}

#pragma mark - 弹窗方法
- (void)headViewChange:(UITapGestureRecognizer *)tapGesture {
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil                                                                             message: nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    // 添加Button
    [alertController addAction: [UIAlertAction actionWithTitle: @"从相册中获取" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        JPPhotoPickManager *pickManager = [JPPhotoPickManager shareInstance];
        [pickManager presentPicker:1
                            target:self
                     callBackBlock:^(NSDictionary *infoDict, BOOL isCancel) {
                         self.imageview.image = [infoDict valueForKey:UIImagePickerControllerOriginalImage];
                         
                         NSString *paths = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
                         NSString *casesPath = [paths stringByAppendingPathComponent:@"image.data"];
                         [NSKeyedArchiver archiveRootObject:@[self.imageview.image] toFile:casesPath];
                         // 发送一个通知
                         [[NSNotificationCenter defaultCenter] postNotificationName:@"changeName" object:self];
                     }];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"拍照" style: UIAlertActionStyleDefault handler:nil]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    
    [self presentViewController: alertController animated: YES completion: nil];
}

/**
 *  设置姓名
 */
- (void)setName:(NSIndexPath *)indexPath {
    // 1.实例化alert:alertControllerWithTitle
    NSString *title;
    if (indexPath.row == 0) {
        title = @"修改姓名";
    } else if (indexPath.row == 2) {
        title = @"修改证件号码";
    } else if (indexPath.row == 3) {
        title = @"修改联系方式";
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    // 获取对应的cell
    JPInformationTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    // 2.实例化按钮:actionWithTitle
    // 为防止block与控制器间循环引用，我们这里需用__weak来预防
    __weak typeof(alert) wAlert = alert;
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        // 点击确定按钮的时候, 会调用这个block
        cell.inforLabel.text = [wAlert.textFields.firstObject text];
        
        if(indexPath.row == 0){
            // 保存到数据库
            NSString *insertSQL = @"update t_person set name=? where id=?;";
            [self update:insertSQL date:cell.inforLabel.text index:@(1)];
            
            // 发送一个通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeName" object:self];
            
            
        }else if(indexPath.row == 2){
            // 保存到数据库
            NSString *insertSQL = @"update t_person set IDNumber=? where id=?;";
            [self update:insertSQL date:cell.inforLabel.text index:@(1)];
            
        }else if(indexPath.row == 3){
            // 保存到数据库
            NSString *insertSQL = @"update t_person set tell=? where id=?;";
            [self update:insertSQL date:cell.inforLabel.text index:@(1)];
        }
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    // 添加文本框(只能添加到UIAlertControllerStyleAlert的样式，如果是preferredStyle:UIAlertControllerStyleActionSheet则会崩溃)
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        
        textField.text = cell.inforLabel.text;
    }];
    
    [self presentViewController:alert animated:YES completion:nil];
}

/**
 *  设置性别
 */
- (void)setGender:(NSIndexPath *)indexPath {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil                                                                             message: nil preferredStyle:UIAlertControllerStyleActionSheet];
    //添加Button
    [alertController addAction: [UIAlertAction actionWithTitle: @"女" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        JPInformationTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.inforLabel.text = @"女";
        NSString *updateSQL = @"update t_person set sex=? where id=?;";
        [self update:updateSQL date:cell.inforLabel.text index:@(1)];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"男" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        JPInformationTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        
        cell.inforLabel.text = @"男";
        NSString *updateSQL = @"update t_person set sex=? where id=?;";
        [self update:updateSQL date:cell.inforLabel.text index:@(1)];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    
    [self presentViewController: alertController animated: YES completion: nil];
}

/**
 *  设置其他信息
 */
- (void)setPrompt:(NSIndexPath *)indexPath {
    
    JPSecondViewController *second = [[JPSecondViewController alloc] init];
    
    second.indexPath = indexPath;
    //1. 自定义呈现的样式
    second.modalPresentationStyle = UIModalPresentationCustom;
    second.transitioningDelegate = self;
    
    [self presentViewController:second animated:YES completion:nil];
    
    JPInformationTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    
    void(^complection)() = ^(NSString *name) {
        if (indexPath.row == 4) {
            cell.inforLabel.text = [NSString stringWithFormat:@"%@CM",name];
            NSString *insertSQL = @"update t_person set height=? where id=?;";;
            [self update:insertSQL date:cell.inforLabel.text index:@(1)];
            
        } else if (indexPath.row == 5) {
            cell.inforLabel.text = [NSString stringWithFormat:@"%@KG",name];
            NSString *insertSQL = @"update t_person set weight=? where id=?;";
            [self update:insertSQL date:cell.inforLabel.text index:@(1)];
            
        } else if (indexPath.row == 6) {
            cell.inforLabel.text = name;
            NSString *insertSQL = @"update t_person set native=? where id=?;";
            [self update:insertSQL date:cell.inforLabel.text index:@(1)];
            
        } else {
            cell.inforLabel.text = name;
            NSString *insertSQL = @"update t_person set address=? where id=?;";
            [self update:insertSQL date:cell.inforLabel.text index:@(1)];
        }
    };
    second.completion = complection;
}

#pragma mark - UIViewControllerTransitioningDelegate

- (nullable UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(nullable UIViewController *)presenting sourceViewController:(UIViewController *)source {
    
    JPPresentationController *presentationController = [[JPPresentationController alloc] initWithPresentedViewController:presented presentingViewController:source];
    
    return presentationController;
}

/**
 *  更新数据库的方法
 */
- (void)update:(NSString *)updateSQL date:(NSString *)date index:(id)index {
    [_manager inDatabase:^(FMDatabase *db) {
        // 执行新增语句
        BOOL isOk = [db executeUpdate:updateSQL,date,index];
        if (isOk) {
            NSLog(@"更新成功");
        } else {
            NSLog(@"更新失败");
        }
    }];
}

/**
 *  新增数据
 */
- (void)update:(NSString *)updateSQL date:(NSString *)date {
    [_manager inDatabase:^(FMDatabase *db) {
        // 执行新增语句
        BOOL isOk = [db executeUpdate:updateSQL,date];
        if (isOk) {
            NSLog(@"更新成功");
        } else {
            NSLog(@"更新失败");
        }
    }];
}

@end
